window.onload = function () {
    init();
};

//初始化购物车界面数据
async function init() {
    let shop = await ajaxGet("/shop/findByUserId");

    //查询对应用户的商品信息，放入表格中
    let str = "";
    let total = 0;
    for (let i = 0; i < shop.length; i++) {
       let shopInfo = shop[i];

       let money = shopInfo.productBean.productPrice * shopInfo.num;
       total += money;
       str += `<tr>
                    <td>${shopInfo.productBean.productName}</td> 
                    <td>${shopInfo.productBean.productPrice}</td> 
                    <td>${shopInfo.productBean.productAddress}</td> 
                    <td><input type="number" min="1" id="${shopInfo.shopId}" value="${shopInfo.num}" onblur="update(${shopInfo.shopId},this.value)"></td> 
                    <td>${money}</td> 
                    <td><a href="javascript:del(${shopInfo.shopId})">移除商品</a></td> 
               </tr>`;
    }
    //往id为shopData的<tbody>添加数据
    $("shopData").innerHTML = str;
    $("total").innerHTML = total;
    $("a").href = "/html/custom/addOrder.html?total="+total
}

async function update(shopId, num) {
    var info = await ajaxGet("/shop/update", {
        shopId: shopId,
        num: num
    });
    init();
}

async function del(shopId) {
    var info = await ajaxGet("/shop/del",{
        shopId:shopId
    });
    if(info == "ok"){
        location.href = "/html/custom/shop.html";
    }else {
        alert("移除失败请重试")
    }
}


